package com.gitee.cashzhang27.test.boot.reactive.webflux.handler;

import static org.springframework.web.reactive.function.server.ServerResponse.ok;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/03/27 11:28
 */
@Component
public class TimeHandler {

  public Mono<ServerResponse> getTime(ServerRequest serverRequest) {
    return ok().contentType(MediaType.TEXT_PLAIN)
        .body(Mono.just("Now is " + new SimpleDateFormat("HH:mm:ss").format(new Date())),
            String.class);
  }

  public Mono<ServerResponse> getDate(ServerRequest serverRequest) {
    return ok().contentType(MediaType.TEXT_PLAIN)
        .body(Mono.just("Today is " + new SimpleDateFormat("yyyy-MM-dd").format(new Date())),
            String.class);
  }

  public Mono<ServerResponse> sendTimePerSec(ServerRequest serverRequest) {
    // MediaType.TEXT_EVENT_STREAM表示Content-Type为text/event-stream，即SSE；
    return ok().contentType(MediaType.TEXT_EVENT_STREAM).body(
        // 利用interval生成每秒一个数据的流。
        Flux.interval(Duration.ofSeconds(1)).
            map(l -> new SimpleDateFormat("HH:mm:ss").format(new Date())),
        String.class);
  }
}
